/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.migo.api;

import com.migo.annotation.IgnoreAuth;
import com.migo.defence.RtCode;
import com.migo.entity.UserinfoInternationEntity;
import com.migo.service.TokenService;
import com.migo.service.UserinfoInternationService;
import com.migo.utils.*;
import com.migo.validator.Assert;
import com.migo.view.UserinfoView;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.omg.CORBA.portable.ApplicationException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * API登录授权
 *
 * @author 知秋
 * @email fei6751803@163.com
 */
@RestController
@RequestMapping("/api")
public class ApiLoginController {
//    @Autowired
//    private UserService userService;


    @Autowired
    private UserinfoInternationService userinfoInternationService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    AppMailUtil appMailUtil;


    @Value("${checkPhoneNumber}")
    String checkPhoneNumber;


    @Autowired
    RedisLimit redisLimit;

    /**
     * 注销用户
     */
    @IgnoreAuth
    @RequestMapping(value = "userLogOut", produces = "application/json;charset=utf-8;")
    public R userLogOut(@RequestParam Map<String, String> params) {
        String userId = params.get("userId");
        try {
            Assert.isBlank(userId, "userId is null");
            UserinfoInternationEntity user = userinfoInternationService.queryUser(userId);
            user.setUseremail("LogOut@powervision.me");
            user.setUserphone("18800000000");
            user.setNickname("LogOut");
            userinfoInternationService.update(user);
            return R.ok();
        } catch (Exception e) {
            return R.error(RtCode.ServerError.getCode(), RtCode.ServerError.getMsg());
        }
    }

    /**
     * 修改密码
     */
//    @SysLog("修改密码")
    @IgnoreAuth
    @RequestMapping(value = "modiyPassword", produces = "application/json;charset=utf-8;")
    public R modiyPassword(@RequestParam Map<String, String> params) {
        String userId = params.get("userId");
        String password = params.get("password");
        String newPassword = params.get("newPassword");
        try {
            Assert.isBlank(userId, "userId is null");
            Assert.isBlank(password, "password is null");
            Assert.isBlank(newPassword, "newPassword is null");
            //保留version+ 第一版需求
            password = MD5.encrypt(password);
            UserinfoInternationEntity user = userinfoInternationService.queryUser(userId);
            if (user.getPassword().equals(password)) {
                //sha256加密
                newPassword = MD5.encrypt(newPassword);
                user.setPassword(newPassword);
                userinfoInternationService.update(user);
                return R.ok();
            } else {
                return R.error(RtCode.PasswordError.getCode(), RtCode.PasswordError.getMsg());
            }
        } catch (Exception e) {
            return R.error(RtCode.ServerError.getCode(), RtCode.ServerError.getMsg());
        }
    }


    /**
     * 注册国际短信验证码
     */
    @IgnoreAuth
    @RequestMapping(value = "sendValidation", produces = "application/json;charset=utf-8;")
    public R sendValidation(@RequestParam Map<String, Object> params, HttpServletRequest request) {
        String ip = IPUtils.getIpAddr(request);
        //IP 防刷 临时策略  2022 11 24 晚
        if (!redisLimit.isActionAllowed("sendValidation", ip, 30000, 1)) {
            return R.error(RtCode.ServerError.getCode(), RtCode.ServerError.getMsg());
        }
        String country_code = (String) params.get("country_code");
        String phone_code = (String) params.get("phone_code");
        String userPhone = (String) params.get("userPhone");
        String code = GenCodeUtil.genCode();
        try {
          /*  String validation = checkPhoneNumber(country_code, userPhone);
            boolean b = Integer.parseInt(JsonUtils.getMapFromJson(validation).get("code").toString()) == 1 ? false : true;*/
            if (true) {
                ExecutorService threadPool = ThreadPoolUtils.getThreadPool();
                if (country_code.equals("CN")) {    //发送国内验证码短信
                    threadPool.execute(new PhoneUtilRunable(code, userPhone, ip));
                } else { //发送国际验证码短信
//                    threadPool.execute(new PhoneInternationalUtilRunable(code, phone_code + "" + userPhone, ip));
                }
                redisTemplate.delete(userPhone);
                redisTemplate.boundValueOps(userPhone).set(code);
                redisTemplate.boundValueOps(userPhone).expire(300, TimeUnit.SECONDS);
                Map<String, String> obj = new HashMap<>();
                obj.put("userPhone", userPhone);
                obj.put("vCode", code);
                return R.ok().put("data", obj);
            } else {
                return R.error(RtCode.ReqParamIsNull.getCode(), RtCode.ReqParamIsNull.getMsg());
            }

        } catch (Exception e) {
            return R.error(RtCode.ServerError.getCode(), RtCode.ServerError.getMsg());
        }
    }



    /**
     * 检测手机号码格式
     *
     * @param country_code
     * @param phone
     * @return
     */
    public String checkPhoneNumber(String country_code, String phone) {
        List<NameValuePair> formparams = new ArrayList<NameValuePair>();
        formparams.add(new BasicNameValuePair("country_code", country_code));
        formparams.add(new BasicNameValuePair("phone", phone));
        String result = new HttpClientUtils().request(formparams, checkPhoneNumber);
        return result;
    }


    public R queryReturnUser(UserinfoInternationEntity user) throws ApplicationException {
        UserinfoView view = new UserinfoView();
        BeanUtils.copyProperties(user, view);
        view.setUserId(user.getUserid());
        view.setHeadImage(user.getHeadimage());
        NullToString.nullConverNullString(view);
        //生成token
        Map<String, Object> map = tokenService.createToken(user.getUserid());
        map.put("user", view);
        return R.ok().put("data", map);
    }


    public R saveReturnUser(UserinfoInternationEntity user) throws ApplicationException {
        userinfoInternationService.register(user);
        user = userinfoInternationService.queryUser(user.getUserid());
        UserinfoView view = new UserinfoView();
        BeanUtils.copyProperties(user, view);
        view.setUserId(user.getUserid());
        view.setHeadImage(user.getHeadimage());
        NullToString.nullConverNullString(view);
        //生成token
        Map<String, Object> map = tokenService.createToken(user.getUserid());
        map.put("user", view);
        return R.ok().put("data", map);
    }

    public R FilterLogin(Map<String, String> params) throws ApplicationException {

        UserinfoInternationEntity user = userinfoInternationService.queryUserExist(params);
        return queryReturnUser(user);
    }

    /**
     * 手机短信验证登录
     */
    @IgnoreAuth
    @RequestMapping(value = "phoneValidationLogin", produces = "application/json;charset=utf-8;")
    public R phoneValidationLogin(@RequestParam Map<String, String> params, HttpServletRequest request) {
        try {
            String ip = IPUtils.getIpAddr(request);
            String mobile = params.get("mobile");
            String code = params.get("code");
            Assert.isBlank(mobile, "phone number is null");
            Assert.isBlank(code, "password is null");
            //添加自然账户  用于审核
            if (mobile.equals("18310060988")) {
                return FilterLogin(params);
            }


            boolean b = redisTemplate.hasKey(mobile);
            if (!b) {
                return R.error(RtCode.AuthCodeError.getCode(), RtCode.AuthCodeError.getMsg());
            }
            //判断手机号是否存在  校验验证码--判断是否存在--存在返回  or 不存在  -插入  -返回
            String rCode = redisTemplate.boundValueOps(mobile).get();
            if (rCode.equals(code)) {
                UserinfoInternationEntity user = userinfoInternationService.queryUserExist(params);
                if (user == null) {
                    String uuid = UUID.randomUUID() + "";
                    user = new UserinfoInternationEntity();
                    user.setUserid(uuid);
                    user.setUseremail("");
                    user.setUserReqIp(ip);
                    user.setAddtime(DateUtil.getNow());
                    user.setVersion("2.0");
                    user.setUserphone(mobile);
                    user.setApptype("4");
                    user.setLogintype("2");  //短信验证码登录
                    // user.setDeviceType("pvmg10");
                    user.setTemp("PVMG10");
                    return saveReturnUser(user);
                } else {
                    return queryReturnUser(user);
                }
            } else {
                return R.error(RtCode.AuthCodeError.getCode(), RtCode.AuthCodeError.getMsg());
            }
        } catch (Exception e) {
            return R.error(RtCode.ServerError.getCode(), RtCode.ServerError.getMsg());
        }
    }


    /**
     * 邮箱验证登录
     */
//    @SysLog("邮箱注册")
    @IgnoreAuth
    @RequestMapping(value = "emailValidationLogin", produces = "application/json;charset=utf-8;")
    public R emailValidationLogin(@RequestParam Map<String, String> params, HttpServletRequest request) {
        String ip = IPUtils.getIpAddr(request);
        String email = params.get("email");
        String code = params.get("code");

        boolean b = redisTemplate.hasKey(email);
        if (!b) {
            return R.error(RtCode.AuthCodeError.getCode(), RtCode.AuthCodeError.getMsg());
        }
        String rCode = redisTemplate.boundValueOps(email).get();
        try {
            if (rCode.equals(code)) {
                UserinfoInternationEntity user = userinfoInternationService.queryUserExist(params);
                if (user == null) {
                    String uuid = UUID.randomUUID() + "";
                    user = new UserinfoInternationEntity();
                    user.setUserid(uuid);
                    user.setUseremail(email);
                    user.setUserReqIp(ip);
                    user.setVersion("2.0");
                    user.setAddtime(DateUtil.getNow());
                    user.setUserphone("");
                    user.setApptype("4");
                    user.setLogintype("2");  //短信验证码登录
                    user.setDeviceType("pvmg10");
                    return saveReturnUser(user);
                } else {
                    return queryReturnUser(user);
                }
            } else {
                return R.error(RtCode.AuthCodeError.getCode(), RtCode.AuthCodeError.getMsg());
            }
        } catch (Exception e) {
            return R.error(RtCode.ServerError.getCode(), RtCode.ServerError.getMsg());
        }
    }


    /**
     * 注册发送验证码
     */
    @IgnoreAuth
    @RequestMapping(value = "verificationCode", produces = "application/json;charset=utf-8;")
    public R verificationCode(@RequestParam Map<String, Object> params, HttpServletRequest request) {
        String ip = IPUtils.getIpAddr(request);
        String userPhone = (String) params.get("userPhone");
        String code = GenCodeUtil.genCode();
        try {
            ExecutorService threadPool = ThreadPoolUtils.getThreadPool();
            threadPool.execute(new PhoneUtilRunable(code, userPhone, ip));
            redisTemplate.delete(userPhone);
            redisTemplate.boundValueOps(userPhone).set(code);
            redisTemplate.boundValueOps(userPhone).expire(300, TimeUnit.SECONDS);
            Map<String, String> obj = new HashMap<>();
            obj.put("userPhone", userPhone);
            obj.put("vCode", code);
            return R.ok().put("data", obj);
        } catch (Exception e) {
            return R.error("send verification code error.");
        }
    }


    /**
     * 注册发送验证码
     */
//    @SysLog("发送邮箱验证码")
    @IgnoreAuth
    @RequestMapping(value = "sendEmail", produces = "application/json;charset=utf-8;")
    public R sendEmail(@RequestParam Map<String, Object> params, HttpServletRequest request) {
        String usermail = (String) params.get("userEmail");
        String actionType = (String) params.get("actionType");
        String language = (String) params.get("language");
        String VerificationCode = null;
        try {
            VerificationCode = PhoneMassage.getPhoneMassage()
                    .createSMSCode();
            boolean flag = appMailUtil.sendMail(VerificationCode, language, usermail,
                    actionType);
            if (flag) {
                return R.ok();
            } else {
                return R.error(RtCode.EmailSendFail.getCode(), RtCode.EmailSendFail.getMsg());
            }
        } catch (Exception e) {
            e.printStackTrace();
            return R.error(RtCode.ServerError.getCode(), RtCode.ServerError.getMsg());
        }
    }


    /**
     * 手机登录
     */
//    @SysLog("手机登录")
    @IgnoreAuth
    @RequestMapping(value = "phoneLogin", produces = "application/json;charset=utf-8;")
    public R phoneLogin(@RequestParam Map<String, String> params) {
        try {
            String mobile = params.get("mobile");
            String password = params.get("password");
            Assert.isBlank(mobile, "phone number is null");
            Assert.isBlank(password, "password is null");
            //保留version+ 第一版需求
            password = MD5.encrypt(password);
            params.put("password", password);
            UserinfoInternationEntity user = userinfoInternationService.phoneLogin(params);
            if (user == null) {
                return R.error(RtCode.IDOrPassWordError.getCode(), RtCode.IDOrPassWordError.getMsg());
            }
            String userId = user.getUserid();
            UserinfoView view = new UserinfoView();
            BeanUtils.copyProperties(user, view);
            view.setUserId(user.getUserid());
            view.setHeadImage(user.getHeadimage());
            NullToString.nullConverNullString(view);
            //生成token
            Map<String, Object> map = tokenService.createToken(userId);
            map.put("user", view);
            return R.ok().put("data", map);
        } catch (Exception e) {
            return R.error(RtCode.ServerError.getCode(), RtCode.ServerError.getMsg());
        }
    }


    /**
     * 邮箱登录
     */
//    @SysLog("邮箱登录")
    @IgnoreAuth
    @RequestMapping(value = "emailLogin", produces = "application/json;charset=utf-8;")
    public R emailLogin(@RequestParam Map<String, String> params) {
        try {
            String email = params.get("email");
            String password = params.get("password");
            Assert.isBlank(email, "user email is null");
            Assert.isBlank(password, "password is null");
            //用户登录
            //保留version+ 第一版需求
            password = MD5.encrypt(password);
            params.put("password", password);
            UserinfoInternationEntity user = userinfoInternationService.emailLogin(params);
            if (user == null) {
                return R.error(RtCode.IDOrPassWordError.getCode(), RtCode.IDOrPassWordError.getMsg());
            }
            String userId = user.getUserid();
            UserinfoView view = new UserinfoView();
            BeanUtils.copyProperties(user, view);
            view.setUserId(user.getUserid());
            view.setHeadImage(user.getHeadimage());
            NullToString.nullConverNullString(view);
            //生成token
            Map<String, Object> map = tokenService.createToken(userId);
            map.put("user", view);
            return R.ok().put("data", map);
        } catch (Exception e) {
            return R.error(RtCode.ServerError.getCode(), RtCode.ServerError.getMsg());
        }
    }

    /**
     * 邮箱注册
     */
//    @SysLog("邮箱注册")
    @IgnoreAuth
    @RequestMapping(value = "emailRegister", produces = "application/json;charset=utf-8;")
    public R emailRegister(@RequestParam Map<String, String> params, HttpServletRequest request) {
        String ip = IPUtils.getIpAddr(request);
        String email = params.get("email");
        String code = params.get("code");
        String rCode = redisTemplate.boundValueOps(email).get();
        try {
            if (rCode.equals(code)) {
                UserinfoInternationEntity user = userinfoInternationService.queryUserExist(params);
                if (user == null) {
                    String uuid = UUID.randomUUID() + "";
                    params.put("ip", ip);
                    params.put("mobile", "");
                    params.put("uuid", uuid);
                    userinfoInternationService.register(params);
                    user = userinfoInternationService.queryUser(uuid);
                    UserinfoView view = new UserinfoView();
                    BeanUtils.copyProperties(user, view);
                    view.setUserId(user.getUserid());
                    view.setHeadImage(user.getHeadimage());
                    NullToString.nullConverNullString(view);
                    return R.ok().put("data", view);
                } else {
                    return R.error(RtCode.EmailExists.getCode(), RtCode.EmailExists.getMsg());
                }
            } else {
                return R.error(RtCode.AuthCodeError.getCode(), RtCode.AuthCodeError.getMsg());
            }
        } catch (Exception e) {
            return R.error(RtCode.ServerError.getCode(), RtCode.ServerError.getMsg());
        }
    }

    /**
     * 手机注册
     */
//    @SysLog("手机注册")
    @IgnoreAuth
    @RequestMapping(value = "phoneRegister", produces = "application/json;charset=utf-8;")
    public R phoneRegister(@RequestParam Map<String, String> params, HttpServletRequest request) {
        String ip = IPUtils.getIpAddr(request);
        String mobile = params.get("mobile");
        String code = params.get("code");
        String rCode = redisTemplate.boundValueOps(mobile).get();
        try {
            if (rCode.equals(code)) {
                UserinfoInternationEntity user = userinfoInternationService.queryUserExist(params);
                if (user == null) {
                    String uuid = UUID.randomUUID() + "";
                    params.put("ip", ip);
                    params.put("email", "");
                    params.put("uuid", uuid);
                    params.put("version", "2.0");
                    userinfoInternationService.register(params);
                    user = userinfoInternationService.queryUser(uuid);
                    UserinfoView view = new UserinfoView();
                    BeanUtils.copyProperties(user, view);
                    view.setUserId(user.getUserid());
                    view.setHeadImage(user.getHeadimage());
                    NullToString.nullConverNullString(view);
                    return R.ok().put("data", view);
                } else {
                    return R.error(RtCode.PhoneExists.getCode(), RtCode.PhoneExists.getMsg());
                }
            } else {
                return R.error(RtCode.AuthCodeError.getCode(), RtCode.AuthCodeError.getMsg());
            }
        } catch (Exception e) {
            return R.error(RtCode.ServerError.getCode(), RtCode.ServerError.getMsg());
        }
    }


    /**
     * 绑定手机号
     */
    @IgnoreAuth
    @RequestMapping(value = "changePhone", produces = "application/json;charset=utf-8;")
    public R changePhone(@RequestParam Map<String, String> params, HttpServletRequest request) {
        String userId = params.get("userId");
        String mobile = params.get("mobile");
        String code = params.get("code");
        Assert.isBlank(userId, "userId is null");
        Assert.isBlank(mobile, "phone number is null");
        Assert.isBlank(code, "code message is null");
        String rCode = redisTemplate.boundValueOps(mobile).get();
        if (rCode.equals(code)) {
            UserinfoInternationEntity user = userinfoInternationService.queryUser(userId);
            //检测是否有重复账户
            Map<String, String> exisParams = new HashMap<>();
            exisParams.put("mobile", mobile);
            exisParams.put("password", user.getPassword());
            UserinfoInternationEntity exisUser = userinfoInternationService.queryUserExist(exisParams);
            //如果不存在相同账户才可以更改
            if (exisUser == null) {
                user.setUserphone(mobile);
                userinfoInternationService.update(user);
                return R.ok();
            } else {
                return R.error(RtCode.PhoneExists.getCode(), RtCode.PhoneExists.getMsg());
            }
        } else {
            return R.error(RtCode.RtNull.getCode(), RtCode.RtNull.getMsg());
        }
    }


    /**
     * 找回手机密码
     */
    @IgnoreAuth
    @RequestMapping(value = "retrieveMobilePassword", produces = "application/json;charset=utf-8;")
    public R retrieveMobilePassword(@RequestParam Map<String, String> params, HttpServletRequest request) {
        String password = params.get("password");
        String mobile = params.get("mobile");
        String code = params.get("code");
        Assert.isBlank(password, "password is null");
        Assert.isBlank(mobile, "phone number is null");
        Assert.isBlank(code, "code message is null");
        boolean b = redisTemplate.hasKey(mobile);
        if (b) {
            String rCode = redisTemplate.boundValueOps(mobile).get();
            //以下有冗余代码
            if (rCode.equals(code)) {
                UserinfoInternationEntity user = userinfoInternationService.queryUserExist(params);
                if (user == null) {
                    return R.error(RtCode.RtNull.getCode(), RtCode.RtNull.getMsg());
                }
                ////保留version+ 第一版需求
                password = MD5.encrypt(password);
                user.setPassword(password);
                userinfoInternationService.update(user);
                return R.ok();
            } else {
                return R.error(RtCode.AuthCodeError.getCode(), RtCode.AuthCodeError.getMsg());
            }
        } else {
            return R.error(RtCode.IDNotExists.getCode(), RtCode.IDNotExists.getMsg());
        }
    }

    /**
     * 找回手机密码
     */
    @IgnoreAuth
    @RequestMapping(value = "retrieveEmailPassword", produces = "application/json;charset=utf-8;")
    public R retrieveMailPassword(@RequestParam Map<String, String> params, HttpServletRequest request) {
        String password = params.get("password");
        String email = params.get("email");
        String code = params.get("code");
        Assert.isBlank(password, "password is null");
        Assert.isBlank(email, "mail number is null");
        Assert.isBlank(code, "code message is null");
        String rCode = redisTemplate.boundValueOps(email).get();
        //以下有冗余代码
        if (rCode.equals(code)) {
            UserinfoInternationEntity user = userinfoInternationService.queryUserExist(params);
            if (user == null) {
                return R.error(RtCode.RtNull.getCode(), RtCode.RtNull.getMsg());
            }
            //保留version+ 第一版需求
            password = MD5.encrypt(password);
            user.setPassword(password);
            userinfoInternationService.update(user);
            return R.ok();
        }
        return R.error(RtCode.RtNull.getCode(), RtCode.RtNull.getMsg());
    }


    /**
     * 20191125-AP03版本增加更换邮箱
     * 为了和旧版本隔离，返回结果有变化
     */
//    @SysLog("更换邮箱")
    @IgnoreAuth
    @RequestMapping(value = "bindEmail", produces = "application/json;charset=utf-8;")
    public R bindEmail(@RequestParam Map<String, String> params) {
        String userId = params.get("userId");
        String email = params.get("email");
        String code = params.get("code");
        Assert.isBlank(userId, "userId is null");
        Assert.isBlank(email, "email number is null");
        Assert.isBlank(code, "code message is null");

        try {
            boolean b = redisTemplate.hasKey(email);
            if (!b) {
                return R.error(RtCode.AuthCodeError.getCode(), RtCode.AuthCodeError.getMsg());
            }
            String rCode = redisTemplate.boundValueOps(email).get();
            if (rCode.equals(code)) {
                UserinfoInternationEntity user = userinfoInternationService.queryUser(userId);
                //检测是否有重复账户
                Map<String, String> exisParams = new HashMap<>();
                exisParams.put("email", email);
                exisParams.put("password", user.getPassword());
                UserinfoInternationEntity exisUser = userinfoInternationService.queryUserExist(exisParams);
                //如果不存在相同账户才可以更改
                if (exisUser == null) {
                    user.setUseremail(email);
                    userinfoInternationService.update(user);
                    return R.ok();
                } else {
                    return R.error(RtCode.EmailExists.getCode(), RtCode.EmailExists.getMsg());
                }
            } else {
                return R.error(RtCode.AuthCodeError.getCode(), RtCode.AuthCodeError.getMsg());
            }
        } catch (Exception e) {
            return R.error(RtCode.ServerError.getCode(), RtCode.ServerError.getMsg());
        }
    }


    /**
     * 20191125-AP03版本增加绑定手机号码
     * 为了和旧版本隔离，返回结果有变化
     */
    @IgnoreAuth
    @RequestMapping(value = "bindPhone", produces = "application/json;charset=utf-8;")
    public R bindPhone(@RequestParam Map<String, String> params, HttpServletRequest request) {
        String userId = params.get("userId");
        String mobile = params.get("mobile");
        String code = params.get("code");
        Assert.isBlank(userId, "userId is null");
        Assert.isBlank(mobile, "phone number is null");
        Assert.isBlank(code, "code message is null");

        try {
            boolean b = redisTemplate.hasKey(mobile);
            if (!b) {
                return R.error(RtCode.AuthCodeError.getCode(), RtCode.AuthCodeError.getMsg());
            }
            String rCode = redisTemplate.boundValueOps(mobile).get();
            if (rCode.equals(code)) {
                UserinfoInternationEntity user = userinfoInternationService.queryUser(userId);
                //检测是否有重复账户
                Map<String, String> exisParams = new HashMap<>();
                exisParams.put("mobile", mobile);
                exisParams.put("password", user.getPassword());
                UserinfoInternationEntity exisUser = userinfoInternationService.queryUserExist(exisParams);
                //如果不存在相同账户才可以更改
                if (exisUser == null) {
                    user.setUserphone(mobile);
                    userinfoInternationService.update(user);
                    return R.ok();
                } else {
                    return R.error(RtCode.PhoneExists.getCode(), RtCode.PhoneExists.getMsg());
                }
            } else {
                return R.error(RtCode.AuthCodeError.getCode(), RtCode.AuthCodeError.getMsg());
            }
        } catch (Exception e) {
            return R.error(RtCode.ServerError.getCode(), RtCode.ServerError.getMsg());
        }
    }

    /**
     * 更换邮箱
     */
//    @SysLog("更换邮箱")
    @IgnoreAuth
    @RequestMapping(value = "changeEmail", produces = "application/json;charset=utf-8;")
    public R changeEmail(@RequestParam Map<String, String> params) {
        String userId = params.get("userId");
        String email = params.get("email");
        String code = params.get("code");
        Assert.isBlank(userId, "userId is null");
        Assert.isBlank(email, "email number is null");
        Assert.isBlank(code, "code message is null");
        String rCode = redisTemplate.boundValueOps(email).get();
        if (rCode.equals(code)) {
            UserinfoInternationEntity user = userinfoInternationService.queryUser(userId);
            //检测是否有重复账户
            Map<String, String> exisParams = new HashMap<>();
            exisParams.put("email", email);
            exisParams.put("password", user.getPassword());
            UserinfoInternationEntity exisUser = userinfoInternationService.queryUserExist(exisParams);
            //如果不存在相同账户才可以更改
            if (exisUser == null) {
                user.setUseremail(email);
                userinfoInternationService.update(user);
                return R.ok();
            } else {
                return R.error(RtCode.EmailExists.getCode(), RtCode.EmailExists.getMsg());
            }
        } else {
            return R.error(RtCode.RtNull.getCode(), RtCode.RtNull.getMsg());
        }
    }

    /**
     * 更新用户信息
     */
//    @SysLog("更换邮箱")
    @IgnoreAuth
    @RequestMapping(value = "changeUserInfo", produces = "application/json;charset=utf-8;")
    public R changeUserInfo(@RequestParam Map<String, String> params) {
        String userId = params.get("userId");
        String headImage = params.get("headImage");
        String nikeName = params.get("nikeName");
        String country = params.get("country");
        String birthday = params.get("birthday");
        String sex = params.get("sex");
        String signature = params.get("signature");
        Assert.isBlank(userId, "userId is null");
        try {
            UserinfoInternationEntity user = userinfoInternationService.queryUser(userId);
            if (!"".equals(headImage)) {
                user.setHeadimage(headImage);
            }
            if (!"".equals(nikeName)) {
                user.setNickname(nikeName);
            }
            if (!"".equals(country)) {
                user.setCountry(country);
            }
            if (!"".equals(birthday)) {
                user.setBirthday(birthday);
            }
            if (!"".equals(sex)) {
                user.setSex(sex);
            }
            if (!"".equals(signature)) {
                user.setSignature(signature);
            }
            userinfoInternationService.update(user);
            Map<String, Object> map = new HashMap<>();
            UserinfoView view = new UserinfoView();
            BeanUtils.copyProperties(user, view);
            view.setUserId(user.getUserid());
            view.setHeadImage(user.getHeadimage());
            NullToString.nullConverNullString(view);
            map.put("user", view);
            return R.ok().put("data", map);
        } catch (Exception e) {
            return R.error(RtCode.ServerError.getCode(), RtCode.ServerError.getMsg());
        }
    }

}
